//
//  HomeListTableViewController.swift
//  MT
//
//  Created by M on 2019/12/15.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit

/// 网络请求

import RxSwift
import RxDataSources
import Moya
import Result

/// 其他
import JXPagingView
import MJRefresh
import MTCategory

class HomeListTableViewController: UIViewController {
    
    /// 列表展示性别 - 默认为不限
    var displayGenderType: LocalGenderModel.GenderType = .unknown
    
    /// 当前显示控制器
    var currentDisplayingController: UIViewController?
    
    /// 列表展示模型
    var models: [HomeListDetailModel] = [] {
        didSet {
            tableView.models = models
        }
    }
    
    /// MTProvider
    private lazy var provider: MTProvider<HomeApi> = {
        return MTProvider<HomeApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    /// 滑动回调
    var tableViewDidScrollCallBack: ((UIScrollView) -> Swift.Void)?
    lazy var tableView: HomeListTableView = {
        let tv = HomeListTableView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight), style: .grouped)
        tv.contentInset = UIEdgeInsets(top: -StatusBarHeight-NavigationBarHeight, left: 0, bottom: 0, right: 0)
        tv.type = dataDisplayType.rawValue
        tv.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMore))
        tv.emptySetView = ViewFactory.emptySetView { [weak self] in
            guard let weakself = self else { return }
            weakself.dataRequest(isAppendingDatas: false, completion: nil)
        }
        return tv
    }()
    
    @objc
    enum DataDisplayType: Int {
        case hottest = 0
        case latest
    }
    /// 展示数据类型
    var dataDisplayType: DataDisplayType {
        didSet {
            tableView.type = dataDisplayType.rawValue
            reloadAllData()
        }
    }
    
    /// 当前页数
    var currentPage: Int = 0
    
    init(dataDisplayType: DataDisplayType) {
        self.dataDisplayType = dataDisplayType
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: ------------------ Overrides ----------------------
extension HomeListTableViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeUI()
        dataRequest()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if currentDisplayingController != self {        
            self.play()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.pause()
    }
}

// MARK: ------------------ UI 样式初始化 ----------------------
extension HomeListTableViewController {
    
    private func initializeUI() {
        addNotification()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
    }
    
    private func addNotification() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(momet(notification:)), name: GlobalNotificationName.moment.name, object: nil)
        
    }
    
    @objc private func momet(notification: Notification) {
        
        guard let id = notification.userInfo?["id"] as? Int else { return }
        
        provider.rx.requestResult(.moment(blackUserId: id)).subscribe(onNext: { (result: Result<MineInfoListResponseModel, AnyError>, isCache: Bool) in
            switch result {
            case let .success(response):
                if response.code == 200 {
                    for (i, v) in self.models.enumerated() {
                        if let un = v.id, un == id {
                            self.models.remove(at: i)
                            DispatchQueue.main.async {
                                self.tableView.reloadData()
                            }
                            break
                        }
                        continue
                    }
                }
                break
                
            case .failure(_):
                break
            }
        }).disposed(by: disposeBag)
        
    }
    
}

// MARK: ------------------ 数据管理 ----------------------
extension HomeListTableViewController {
    
    /// 请求类型
    private var requestTarget: HomeApi {
        switch dataDisplayType {
        case .hottest:
            return displayGenderType == .unknown ? .hotListWithoutGender(curPage: currentPage) : .hotList(curPage: currentPage, sex: displayGenderType.requestType)
        case .latest:
            return displayGenderType == .unknown ? .latestListWithoutGender(curPage: currentPage) : .latestList(curPage: currentPage, sex: displayGenderType.requestType)
        }
    }
    
    /// 重新加载所有数据
    public func reloadAllData(completion: (() -> Swift.Void)? = nil) {
        currentPage = 0
        models = []
        dataRequest(completion: completion)
    }
    
    /// 加载更多
    @objc
    public func loadMore() {
        dataRequest(isAppendingDatas: true)
    }
    
    /// 数据请求
    private func dataRequest(isAppendingDatas: Bool = false, completion: (() -> Swift.Void)? = nil) {
        provider.rx.requestResult(requestTarget).subscribe(onNext: { [weak self] (result: Result<HomeListDetailReponseModel, AnyError>, isCache: Bool) in
            guard let weakSelf = self else { return }
            weakSelf.tableView.mj_header?.endRefreshing()
            weakSelf.tableView.mj_footer?.endRefreshing()
            
            switch result {
            case .success(let model):
                
                weakSelf.currentPage += 1
                if let result = model.result {
                    if isAppendingDatas {
                        weakSelf.models += result
                    } else {
                        weakSelf.tableView.player.stopCurrentPlayingCell()
                        weakSelf.models = result
                        weakSelf.tableView.playVideo(at: IndexPath(row: 0, section: 0), scrollToTop: false)
                    }
                }
                break
                
            case .failure(_):
                break
                
            }
            
            if let completion = completion {
                completion()
            }
            
        }).disposed(by: disposeBag)
    }
    
}

// MARK: ------------------ 列表性别选择 ----------------------
extension HomeListTableViewController {
    
    public func setGenderType(_ genderType: LocalGenderModel.GenderType, isCurrentPagingController: Bool) {
        displayGenderType = genderType
        reloadAllData { [weak self] in
            guard let weakSelf = self else { return }
            if !isCurrentPagingController {
                weakSelf.tableView.pause()
            }
        }
    }
    
}

// MARK: ------------------ 播放器控制 ----------------------
extension HomeListTableViewController {
    
    /// 播放视频
    public func play() {
        self.tableView.play()
    }
    
    /// 暂停视频
    public func pause() {
        self.tableView.pause()
    }
    
}

// MARK: ------------------ 所有代理 ----------------------
// MARK: ------------------ JXPagingViewListViewDelegate ----------------------
extension HomeListTableViewController: JXPagingViewListViewDelegate {
    
    func listView() -> UIView {
        self.view
    }
    
    func listScrollView() -> UIScrollView {
        self.tableView 
    }
    
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.tableViewDidScrollCallBack = callback
    }
    
    func listDidAppear() {
        self.tableView.play()
    }
    
    func listDidDisappear() {
        self.tableView.pause()
    }
    
}
